import { defineStore } from 'pinia'
import request from '@/utils/request'
import router from '@/router/index'
import { alertMsg } from '@/utils/msg.js'

export const useUserStore = defineStore('user', {
  state: () => ({
    username: '',
    password: '',
    phone: '',
    gender: '',
    token: '',
    isLoading: false,
    error: null,
    roleid: '',
    rules: {
      logpwd: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }
      ],
      logid: [
        {
          required: true,
          message: '请输入名字',
          trigger: 'blur'
        }
      ]
    },
    logForm: {
      logid: '',
      logpwd: ''
    }
  }),
  actions: {
    async slogin() {
      this.isLoading = true
      this.error = null
      console.log(this.logForm)
      try {
        const response = await request.post('/user/login', this.logForm)

        if (response.data.roleid === 1) {
          this.token = response.data.token
          this.roleid = response.data.roleid
          localStorage.setItem('pid', response.data.id)
          localStorage.setItem('token', response.data.token)
          this.clearUser()
          router.push({ name: 'public', query: { id: response.data.id } })
        } else {
          alertMsg(400, '身份错误')
        }
      } catch (error) {
        this.error = error.message
      } finally {
        this.isLoading = false
      }
    },
    clearUser() {
      this.logForm = {
        logid: '',
        logpwd: ''
      }
    },
    async glogin() {
      this.isLoading = true
      this.error = null
      console.log(this.logForm)
      try {
        const response = await request.post('/user/login', this.logForm)

        if (response.data.roleid === 2) {
          this.token = response.data.token
          this.roleid = response.data.roleid
          console.log(response.data)
          localStorage.setItem('gid', response.data.id)

          localStorage.setItem('token', response.data.token)

          this.clearUser()
          router.push({ name: 'feedback', query: { id: response.data.id } })
        } else {
          alertMsg(400, '身份错误')
        }
      } catch (error) {
        this.error = error.message
      } finally {
        this.isLoading = false
      }
    },
    async register(userData) {
      this.isLoading = true
      this.error = null
      console.log(userData)
      try {
        const response = await request.post('/user/register', userData)
        console.log(response.data)
        router.push({ name: 'Login' })
      } catch (error) {
        this.error = error.message
      } finally {
        this.isLoading = false
      }
    },
    logout() {
      this.user = null
      this.token = null
    }
  }
})
